require 'date'

def newfriends(oldfriends)
  friends = Twitter.friend_ids.ids
  if !oldfriends.empty?
      newfriends = friends - oldfriends
      newfriends.each do |friend|
        begin
          puts "New Friend #{Twitter.user(friend).name}"
          #Check our system
          #if we find them check if we're already befriended them once
          #if not check twitter to see if we already follow them
          #if we dont then follow them
        rescue
          Log.new( :exception => e.to_s, :message => e.class.to_s).save
          puts "Exception: #{e}"  
        end
      end
  end
  return friends
end

def karmaise()
  followers = Twitter.follower_ids
  friends = Twitter.friend_ids
  dif = friends.ids - followers.ids
  dif.each do |id|
    begin
      user = Twitter.user(id)
      Twitter.unfollow(user.name)
      puts "Unfollowed #{user.id}"
    rescue Exception=>e
        Log.new( :exception => e.to_s, :message => e.class.to_s).save
        puts "Exception: #{e}"
      end
  end
end



def searchHashtag(hashtag)
    puts "Finding tweets with the hashtag #{hashtag}"
    
    search = Twitter::Search.new
    hashtagresult = search.hashtag("#"+ hashtag).no_retweets.per_page(5).fetch
    hashtagresult.each do |r|
      begin
        puts "#{r.from_user_name}: #{r.text}"
      rescue Exception=>e
        Log.new( :exception => e.to_s, :message => e.class.to_s).save
        puts "Exception: #{e}"
      end
    end
    search.clear
end

def mostpopularfollower()
    
    cursor = -1
    followers = []
    begin
      response = Twitter.followers :cursor => cursor
      followers += response.users
      cursor = response.next_cursor
    end while cursor > 0
    
    return followers.sort{|a, b| a.followers_count <=> b.followers_count}.reverse.first 
    
end

def mostpopularfriend()
    
    cursor = -1
    friends = []
    begin
      response = Twitter.friends :cursor => cursor
      friends += response.users
      cursor = response.next_cursor
    end while cursor > 0
    
    return friends.sort{|a, b| a.followers_count <=> b.followers_count}.reverse.first 
    
end